from flask import  Flask
from flask_cors import  CORS

from flask import request,jsonify
import json

from db import db

app = Flask(__name__)

CORS(app)

app.config['JSON_AS_ASCII'] = False


#测试
@app.route('/text/')
def method_name():
    return jsonify({'code':200,'mas':'hello world 你看好阿萨德'})


def get_data():
    data = request.data
    if data:
        data = json.loads(request.data)
    else:
        data = request.form
    return data






#三方登录返回表
@app.route('/sflogin/')
def sflogin():
    return jsonify({'code':200,'token':'abcdefg12345678','uid':'123456'})


#登录,,授权
@app.route("/shouquan/",methods=["POST","GET"])
def shouquan():
    if request.method=="POST":
        data = get_data()
        #查询有没有三方登录过 
        sql = "select * from sf_login where uid=%d"%(int(data['uid']))
        res = db.find_one(sql)
        #如果有数据 直接登录成功
        if res:
            return jsonify({"code":200,'mas':'欢迎登录'})

        else:
        
            return jsonify({'code':20020,'mas':'请绑定手机号'})
        
    elif request.method=="GET":
        #绑定手机号
            mobile = request.args.get('mobile')
            password = request.args.get('password')
            token = request.args.get('token')
            uid = request.args.get('uid')
            sql1 = "insert into users values(0,'%s','%s')"%(mobile,password)
            db.insert(sql1)
            #获取id 把授权登录加入数据库
            sql2 = "select * from users where mobile='%s'"%(mobile)
            res2 = db.find_one(sql2)
            #把uid  token  user_id 写入三方登录表
            sql3 = "insert into sf_login values(0,%d,'%s',%d)"%(int(res2['id']),token,int(uid))
            db.insert(sql3)
            return jsonify({'code':20020})
















if __name__ == '__main__':
    app.run(debug=True,host='127.0.0.1',port=5000)















